package com.glsc.ngateway.common.api.shortmsg.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.shortmsg.ex.CommonApiException;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;

/**
 * 企微工具类
 *
 * @author xuchang
 */
@Lazy
@Component
public class WorkWechatUtils {

    private static final Logger logger = LoggerFactory.getLogger(WorkWechatUtils.class);
    private static String client;

    @Value("${workWechat.client}")
    public void setClient(String client) {
        WorkWechatUtils.client = client;
    }

    public static MessageResponse<Boolean> sendMsg(@NotNull MessageGenericVo msg) throws IOException, InterruptedException {
        if (CollectionUtil.isEmpty(msg.getOaUserAccounts()) && CollectionUtil.isEmpty(msg.getOaDeptIds())) {
            throw CommonApiException.error("企微消息通知失败：缺少通知人或部门信息");
        }
        logger.info("企微消息通知：{}", msg);
        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                .uri(URI.create(client + "/glzb-api/zb-qywx/b/message/send-agent-message-generic"))
                .method("POST", HttpRequest.BodyPublishers.ofString(JSONObject.toJSONString(msg)))
                .header("Accept", "*/*")
                .header("Accept-Encoding", "gzip, deflate, br")
                .header("Content-Type", "application/json")
                .headers("userAgent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36");
        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> resp = client.send(requestBuilder.build(), HttpResponse.BodyHandlers.ofString());
        logger.info("企微消息通知：{}", resp);
        if (!(HttpStatus.OK.value() == resp.statusCode())) {
            throw CommonApiException.error("请求企微推送消息失败");
        }
        return JSONObject.parseObject(resp.body(), MessageResponse.class);
    }

    /**
     * 发送企微消息参数
     */
    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    @Builder
    @ApiModel("发送通⽤消息信息")
    public static class MessageGenericVo {
        /**
         * {
         * "oaUserAccounts":[
         * "xuchang"
         * ],
         * "msgType":"text",
         * "agentId":"1000071",
         * "text":{
         * "content":"你的快递已到，请携带⼯卡前往邮件中⼼领取。\n出发前可查看<a href=\"http://work.weixin.qq.com\">邮件中⼼视频实况</a>，聪明避开排队。"
         * },
         * "safe":0,
         * "enable_id_trans":0,
         * "enable_duplicate_check":0,
         * "duplicate_check_interval":1800
         * }
         */
        @ApiModelProperty("接收消息成员OA账号")
        private List<String> oaUserAccounts;
        @ApiModelProperty("接收消息部⻔OA id")
        private List<Integer> oaDeptIds;
        @ApiModelProperty("接收消息标签id")
        private List<Integer> tagIds;
        @ApiModelProperty("消息类型")
        @NotNull
        private String msgType;
        @ApiModelProperty("应⽤id")
        @NotNull
        private String agentId;
        @NotNull
        private Map<String, Object> text;
        @Builder.Default
        private int safe = 0;
        @Builder.Default
        private int enable_id_trans = 0;
        @Builder.Default
        private int enable_duplicate_check = 0;
        @Builder.Default
        private int duplicate_check_interval = 1800;
    }


    @AllArgsConstructor
    @NoArgsConstructor
    @Builder
    @Data
    public static class MessageResponse<T> {
        private int code;
        private String msg;
        private T data;
    }
}
